package com.engine.cn.leetcode.link;

/**
 * 合并两个有序链表
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 * 输入：l1 = [1,2,4], l2 = [1,3,4]
 * 输出：[1,1,2,3,4,4]
 */
public class MergeTwoSortedLinkedList {
    public static Node mergeTwoList(Node head1, Node head2) {
        //判空
        if (head1 == null || head2 == null) {
            return head2 == null ? head1 : head2;
        }

        //确定头节点,谁小谁是头
        Node head = head1.val >= head2.val ? head2 : head1;
        //头节点的下一个节点
        Node current1 = head.next;
        //另一个链表的头结点
        Node current2 = head == head1 ? head2 : head1;
        //head不能够动，所以pre指针来走
        Node pre = head;
        //只要有一个链表的节点为空，就结束了
        while (current1 != null && current2 != null) {
            if (current1.val <= current2.val) {
                //pre指针指向current1
                pre.next = current1;
                current1 = current1.next;
            } else {
                //pre指针指向current2
                pre.next = current2;
                current2 = current2.next;
            }
            //pre指针前移
            pre = pre.next;
        }

        //某一个节点走完了
        pre.next = current1 == null ? current2 : current1;
        return head;
    }

    public static void main(String[] args) {
        Node node1 = new Node(1);
        node1.next = new Node(2);
        node1.next.next = new Node(6);

        Node node2 = new Node(1);
        node2.next = new Node(3);
        node2.next.next = new Node(4);
        node2.next.next.next = new Node(8);

        Node head = mergeTwoList(node1, node2);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }
}
